package com.sh.learn.ibeifeng.webservice.axis;

import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.Date;
import org.apache.axis.AxisFault;
import org.apache.axis.Handler;
import org.apache.axis.MessageContext;
import org.apache.axis.handlers.BasicHandler;

public class LogHandler extends BasicHandler{

	// invoke方法是每个handler必须实现的
    public void invoke(MessageContext msgContext) throws AxisFault {
		try {
			// Handler就认作SOAPService
			Handler handler = msgContext.getService();
			// 从描述文件获得要写入的文件名
			String filename = (String)this.getOption("filename");
			if(filename == null || filename.trim().equals("")){
				throw new AxisFault("Server no log file", "No log file for the LogHandler", null, null);
			}
			// 统计调用次数
			Integer count = (Integer)handler.getOption("accesses");
			if(count == null){
				count = new Integer(0);
			}
			count = new Integer(count.intValue()+1);
			// 回写到描述文件
			handler.setOption("accesses", count);
			// 打印
			Date date = new Date();
			// 控制台
			msgContext.getMessage().writeTo(System.out);
			// 日志文件
			String result = date +  "web服务: " + msgContext.getTargetService() + " 使用: " + count + "次";
			// 写出日志到服务端
			FileOutputStream fos = new FileOutputStream(filename, true); // true，追加文本
			PrintWriter pw = new PrintWriter(fos);
			pw.println(result);
			pw.close();
			fos.close();
        } catch (Exception e) {
	        e.printStackTrace();
        }
		
    }
	
	
}
